using FastDevTemplate.DataAccess.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace FastDevTemplate.DataAccess.Config;

public class UserConfiguration : IEntityTypeConfiguration<User>
{
    public void Configure(EntityTypeBuilder<User> modelBuilder)
    {
        modelBuilder
            .HasIndex(e => e.UserName).IsUnique();

        modelBuilder.HasQueryFilter(e => !e.IsDelete);
    }
}

public class PermissionConfiguration : IEntityTypeConfiguration<Permission>
{
    public void Configure(EntityTypeBuilder<Permission> modelBuilder)
    {
        modelBuilder.HasKey(item => item.ID);
    }
}

public class RoleConfiguration : IEntityTypeConfiguration<Role>
{
    public void Configure(EntityTypeBuilder<Role> modelBuilder)
    {
        modelBuilder.HasKey(item => item.ID);
    }
}

public class UserRoleConfiguration : IEntityTypeConfiguration<UserRole>
{
    public void Configure(EntityTypeBuilder<UserRole> modelBuilder)
    {
        modelBuilder
            .HasOne<User>(item => item.User)
            .WithMany(item => item.UserRoles)
            .HasForeignKey(item => item.UserID)
            .OnDelete(DeleteBehavior.Cascade);

        modelBuilder
            .HasOne<Role>(item => item.Role)
            .WithMany(item => item.UserRoles)
            .HasForeignKey(item => item.RoleID)
            .OnDelete(DeleteBehavior.Cascade);
        
        modelBuilder.HasKey(item => new { item.UserID, item.RoleID });
        modelBuilder.HasQueryFilter(e => !e.User.IsDelete);
    }
}

public class RolePermissionConfiguration : IEntityTypeConfiguration<RolePermission>
{
    public void Configure(EntityTypeBuilder<RolePermission> modelBuilder)
    {
        modelBuilder
            .HasOne<Role>(item => item.Role)
            .WithMany(item => item.RolePermissions)
            .HasForeignKey(item => item.RoleID)
            .OnDelete(DeleteBehavior.Cascade);

        modelBuilder
            .HasOne<Permission>(item => item.Permission)
            .WithMany(item => item.RolePermissions)
            .HasForeignKey(item => item.PermissionID)
            .OnDelete(DeleteBehavior.Cascade);
        
        modelBuilder.HasKey(item => new { item.PermissionID, item.RoleID });
    }
}